﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace Rugicon.Outlook
{
    /// <summary>
    /// A classic options form for Rugicon.
    /// </summary>
    public partial class OptionsForm : Form
    {
        /// <summary>
        /// Used to prevent cross-thread callings when binding emoticons sets with its listview. I really miss WPF.
        /// </summary>
        delegate void RefreshEmoticonsSetListDelegate();

        /// <summary>
        /// Used to prevent cross-thread callings when binding emoticons sets with its listview. I really miss WPF.
        /// </summary>
        RefreshEmoticonsSetListDelegate refreshDelegate;

        /// <summary>
        /// Creates an instance of <see cref="OptionsForm"/>.
        /// </summary>
        public OptionsForm()
        {
            InitializeComponent();
            InitializeForm();
        }

        /// <summary>
        /// Sets up the form controls and events.
        /// </summary>
        private void InitializeForm()
        {
            // Link to the feedback site.
            linkFeedback.LinkClicked += (s, e) => { Process.Start(new ProcessStartInfo("https://rugicon.uservoice.com")); };
            
            // Link to the folder where the emoticons are.
            linkAddNewEmoticons.LinkClicked += (s, e) => { Process.Start(new ProcessStartInfo(Configuration.EmoticonsFolder)); };

            // Used to prevent cross-thread callings when binding emoticons sets with its listview. I really miss WPF.
            refreshDelegate = new RefreshEmoticonsSetListDelegate(RefreshEmoticonSetsList);

            // When the emoticon sets might were update, refresh the listview
            Emoticons.EmoticonsChanged += (s, e) => { this.Invoke(refreshDelegate); };

            // Load up the listview
            RefreshEmoticonSetsList();
        }

        public void RefreshEmoticonSetsList()
        {
            listviewEmoticonSets.Items.Clear();
            foreach (EmoticonSet set in Emoticons.GetAllEmoticonSets())
            {
                var item = new ListViewItem { Text = set.Name, };
                item.SubItems.Add(set.Emoticons.Count().ToString());
                listviewEmoticonSets.Items.Add(item);
            }

            // Who let ListView.SetAutoSizeMode as protected? He or she should be arrested.
            listviewEmoticonSets.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
        }
    }
}
